package com.ruoyi.handler.socket;

import cn.hutool.core.collection.ConcurrentHashSet;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class MySocketChannelInboundHandler9083 extends ChannelInboundHandlerAdapter {

    private static ConcurrentHashSet<Channel> onlineChannelSet = new ConcurrentHashSet<>();


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        log.info("9083端口的船只连接成功, channel: {}", channel);

        addOnlineChannel(channel);

        super.channelActive(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        super.channelRead(ctx, msg);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        log.info("9083端口的船只断开连接, channel: {}", channel);

        removeChannel(channel);

        super.channelInactive(ctx);
    }

    public static void addOnlineChannel(Channel channel) {
        onlineChannelSet.add(channel);
    }

    public static void removeChannel(Channel channel) {
        onlineChannelSet.remove(channel);
    }

    public static void sendMsgToAllOnlineChannel(ByteBuf msg) {
        log.info("给9083端口当前所有在线船只发送RTK消息，该端口当前在线船只总数量： {}", onlineChannelSet.size());
        for (Channel channel : onlineChannelSet) {
            log.info("给船端[channel:{}]发送RTK报文消息.", channel);
            //此行代码必须添加，否则发送消息时会报错
            msg.retain();
            channel.writeAndFlush(msg);
        }
    }
}
